package com.meowcook.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.meowcook.common.AppResult;
import com.meowcook.config.AppConfig;
import com.meowcook.controller.MembersController;
import com.meowcook.controller.MessageController;
import com.meowcook.pojo.dto.MessageDTO;
import com.meowcook.pojo.vo.MessageVO;
import com.meowcook.pojo.vo.UserPartIVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-11-15
 * Time: 15:49
 */
@Slf4j
@Component
public class WebSocketServer extends TextWebSocketHandler {
    @Resource
    private MessageController messageController;

    @Resource
    private MembersController membersController;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private OnlineUserManager onlineUserManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("用户{}连接成功", session.getId());
        UserPartIVO user = (UserPartIVO) session.getAttributes().get(AppConfig.USER_SESSION_KEY);
        onlineUserManager.online(session, user.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 解析载荷获取信息
        MessageDTO messageDTO = objectMapper.readValue(message.getPayload(), MessageDTO.class);
        // 获取当前会话的成员id
        AppResult<ArrayList<Long>> membersId = membersController.getMembersId(messageDTO.getSessionId());
        // 信息的持久化处理
        MessageVO messageVO = messageController.createMessage(messageDTO);
        // 获取新信息
        message = new TextMessage(objectMapper.writeValueAsString(messageVO));
        // 消息转发
        for (Long memberId : membersId.getData()) {
            WebSocketSession memberSession = onlineUserManager.getSession(memberId);
            if (memberSession != null) {
                // 给在线的人转发消息
                memberSession.sendMessage(message);
            }
            // 给对应会话的所有人添加未读消息数
            membersController.addUncheckNum(memberId, messageDTO.getSessionId());
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("用户{}异常断开连接", session.getId());
        UserPartIVO user = (UserPartIVO) session.getAttributes().get(AppConfig.USER_SESSION_KEY);
        onlineUserManager.offline(user.getId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("用户{}断开连接", session.getId());
        UserPartIVO user = (UserPartIVO) session.getAttributes().get(AppConfig.USER_SESSION_KEY);
        onlineUserManager.offline(user.getId(), session);
    }
}
